﻿//通用值的转换

var result = "5".Parse<DateTime?>(DateTime.Now);

Console.WriteLine("值是:{0}，数据类型：{1}", result, result.GetType().Name);

Console.ReadKey();

public static class Extensions
{
    public static T Parse<T>(this object value,T defaultValue=default)
    {
        var type = typeof(T);

        try
        {
            var nullableType = Nullable.GetUnderlyingType(type);
            if (nullableType is not null)
            {
                return (T)Convert.ChangeType(value, nullableType);
            }

            return (T)Convert.ChangeType(value, type);
        }
        catch
        {
            return defaultValue;
        }
    }
}